package com.xhs.hawaii.upload.service;

import com.alibaba.druid.util.StringUtils;
import com.qcloud.PicCloud;
import com.qcloud.UploadResult;
import com.qcloud.sign.FileCloudSign;
import com.xhs.hawaii.common.BusinessException;
import com.xhs.hawaii.upload.model.UploadFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


/**
 * 腾讯云上传服务
 *
 * @author chenqunhui
 */
@Service
public class QCloudService {

    @Value("${qcloud.appid}")
    private String appId;
    @Value("${qcloud.bucket}")
    private String bucket;
    @Value("${qcloud.secret_id}")
    private String secretId;
    @Value("${qcloud.secret_key}")
    private String secretKey;
    @Value("${qcloud.sign_expires_in}")
    private String signExpiresIn;

    public String getQCloudDownload(String url) {
        if (url.indexOf("?") != -1) {
            return url.substring(0, url.indexOf("?")) + "?sign=" + this.getQCloudSign();
        } else {
            return url + "?sign=" + this.getQCloudSign();
        }
    }

    public String getQCloudSign() {
        Long expired = System.currentTimeMillis() / 1000 + Long.valueOf(signExpiresIn);
        String sign = FileCloudSign.appSignV2(Integer.valueOf(appId), secretId, secretKey, bucket, expired);
        return sign;
    }

    public UploadFile qCloudUpload(MultipartFile file) {
        try {
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(file.getBytes());
            return upload(byteInputStream, file.getOriginalFilename());
        } catch (IOException e) {
            throw new BusinessException("上传文件失败", e);
        }

    }

    public UploadFile upload(InputStream in, String fileName) {
        PicCloud pc = new PicCloud(Integer.valueOf(appId), secretId, secretKey, bucket);
        String key = null;
        if (!StringUtils.isEmpty(fileName)) {
            int x = fileName.lastIndexOf(".");
            if (x != -1) {
                key = fileName.substring(0, x) + System.currentTimeMillis() + fileName.substring(x);
            } else {
                key = fileName + System.currentTimeMillis();
            }
        } else {
            key = UUID.randomUUID().toString();
        }
        UploadResult result = new UploadResult();
        pc.upload(new BufferedInputStream(in), key, result);
        UploadFile uFile = new UploadFile();
        uFile.setDownloadUrl(result.downloadUrl);
        uFile.setOriginFileName(fileName);
        uFile.setUploadFileName(result.fileId);
        uFile.setUrl(result.url);
        return uFile;
    }
}
